import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';
import { getCurrentUser, isAdmin } from '@/middleware/auth';
import { AuthService } from '@/lib/auth';
import { Role } from '@/lib/db/auth-schema';

/**
 * 获取角色列表
 */
export async function GET(request: NextRequest) {
  try {
    // 验证管理员权限
    let currentUser = getCurrentUser(request);
    
    // 如果getCurrentUser没有返回用户信息，尝试直接验证token
     if (!currentUser) {
       const authHeader = request.headers.get('authorization');
       const cookieHeader = request.headers.get('cookie');
       let token: string | null = null;
       
       if (authHeader && authHeader.startsWith('Bearer ')) {
         token = authHeader.substring(7);
       } else if (cookieHeader) {
         const cookies = cookieHeader.split(';').reduce((acc: any, cookie) => {
           const [key, value] = cookie.trim().split('=');
           acc[key] = value;
           return acc;
         }, {});
         token = cookies['auth-token'] || null;
       }
       
       if (token) {
         const tokenResult = await AuthService.verifyToken(token);
         if (tokenResult.valid && tokenResult.payload) {
           currentUser = tokenResult.payload;
         }
       }
     }
    
    if (!currentUser || !isAdmin(currentUser)) {
      return NextResponse.json(
        { success: false, error: '权限不足' },
        { status: 403 }
      );
    }

    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '20');
    const search = searchParams.get('search') || '';
    const isSystem = searchParams.get('is_system');
    const isActive = searchParams.get('is_active');
    const sortBy = searchParams.get('sort_by') || 'level';
    const sortOrder = searchParams.get('sort_order') || 'asc';

    const db = await getDb();

    // 构建查询过滤器
    const filter: any = {};
    if (search) {
      filter.$or = [
        { name: { $regex: search, $options: 'i' } },
        { display_name: { $regex: search, $options: 'i' } },
        { description: { $regex: search, $options: 'i' } }
      ];
    }
    if (isSystem !== null) filter.is_system = isSystem === 'true';
    if (isActive !== null) filter.is_active = isActive === 'true';

    // 获取角色列表
    const rolesResult = await db.findMany<Role>('roles', filter, {
      page,
      pageSize: limit,
      sortBy,
      sortOrder: sortOrder as 'asc' | 'desc'
    });
    const roles = rolesResult.success ? rolesResult.data || [] : [];

    // 获取总数
    const countResult = await db.count('roles', filter);
    const total = countResult.success ? countResult.data || 0 : 0;

    // 获取统计信息
    const allRolesResult = await db.findMany<Role>('roles', {});
    const allRoles = allRolesResult.success ? allRolesResult.data || [] : [];
    
    const stats = {
      total: allRoles.length,
      active: allRoles.filter(r => r.is_active).length,
      inactive: allRoles.filter(r => !r.is_active).length,
      system: allRoles.filter(r => r.is_system).length,
      custom: allRoles.filter(r => !r.is_system).length
    };

    return NextResponse.json({
      success: true,
      data: roles,
      total,
      page,
      limit,
      stats
    });

  } catch (error) {
    console.error('获取角色列表失败:', error);
    return NextResponse.json(
      { success: false, error: '获取角色列表失败' },
      { status: 500 }
    );
  }
}

/**
 * 创建新角色
 */
export async function POST(request: NextRequest) {
  try {
    // 验证管理员权限
    let currentUser = getCurrentUser(request);
    
    // 如果getCurrentUser没有返回用户信息，尝试直接验证token
    if (!currentUser) {
      const authHeader = request.headers.get('authorization');
      const cookieHeader = request.headers.get('cookie');
      let token: string | null = null;
      
      if (authHeader && authHeader.startsWith('Bearer ')) {
        token = authHeader.substring(7);
      } else if (cookieHeader) {
        const cookies = cookieHeader.split(';').reduce((acc: any, cookie) => {
          const [key, value] = cookie.trim().split('=');
          acc[key] = value;
          return acc;
        }, {});
        token = cookies['auth-token'] || null;
      }
      
      if (token) {
        const tokenResult = await AuthService.verifyToken(token);
        if (tokenResult.valid && tokenResult.payload) {
          currentUser = tokenResult.payload;
        }
      }
    }
    
    if (!currentUser || !isAdmin(currentUser)) {
      return NextResponse.json(
        { success: false, error: '权限不足' },
        { status: 403 }
      );
    }

    const body = await request.json();
    const { name, display_name, description, level, is_active = true } = body;

    // 验证必填字段
    if (!name || !display_name || level === undefined) {
      return NextResponse.json(
        { success: false, error: '缺少必填字段' },
        { status: 400 }
      );
    }

    // 验证角色级别
    if (typeof level !== 'number' || level < 0 || level > 100) {
      return NextResponse.json(
        { success: false, error: '角色级别必须是0-100之间的数字' },
        { status: 400 }
      );
    }

    const db = await getDb();

    // 检查角色名称是否已存在
    const existingRoleResult = await db.findOne<Role>('roles', { name });
    
    if (existingRoleResult.success && existingRoleResult.data) {
      return NextResponse.json(
        { success: false, error: '角色名称已存在' },
        { status: 409 }
      );
    }

    // 创建角色
    const roleId = `role_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    const now = new Date().toISOString();

    const roleData: Partial<Role> = {
      id: roleId,
      name,
      display_name,
      description: description || '',
      level,
      is_system: false, // 用户创建的角色都不是系统角色
      is_active,
      created_at: now,
      updated_at: now
    };

    const createResult = await db.create<Role>('roles', roleData);

    if (!createResult.success) {
      return NextResponse.json(
        { success: false, error: '创建角色失败' },
        { status: 500 }
      );
    }

    return NextResponse.json({
      success: true,
      data: createResult.data,
      message: '角色创建成功'
    });

  } catch (error) {
    console.error('创建角色失败:', error);
    return NextResponse.json(
      { success: false, error: '创建角色失败' },
      { status: 500 }
    );
  }
}